
<input type="file" id="globalFilePicker" class="hide" multiple/>
<link rel="stylesheet" type="text/css" href="/static/lib/webuploader/webuploader.css">
<script type="text/javascript" src="/static/lib/webuploader/webuploader.nolog.min.js"></script>

<script type="text/javascript">
$(function () {
    // 文件上传
    var BASE_URL = "/static/lib/webuploader"
    // 初始化Web Uploader
    var uploader = xnote.createUploader();
    var loadingIndex = 0;

    // 当有文件添加进来的时候
    uploader.on( 'fileQueued', function( file ) {
        // 接受文件
    });


    // 文件上传过程中创建进度条实时显示。
    uploader.on( 'uploadProgress', function( file, percentage ) {
        var percent = (percentage * 100).toFixed(2) + '%';
        console.log('upload process ' + percent)
    });

    uploader.on( 'uploadBeforeSend', function (object, data, headers) {
        $( '#uploadProgress' ).find('.progress').remove();
        data.dirname = "auto";
    })

    // 文件上传成功，给item添加成功class, 用样式标记上传成功。
    uploader.on( 'uploadSuccess', function( file, resp) {
        file.webpath = resp.webpath;

        var webpath = file.webpath;
        var content = 'file://$name'.replace(/\$name/g, file.webpath);
        var inputText = content;

        layer.close(loadingIndex);

        var result = {link: inputText};

        xnote.fire("file.upload", result);
    });

    // 文件上传失败，显示上传出错。
    uploader.on( 'uploadError', function( file ) {
        console.error("uploadError", file);
        layer.close(loadingIndex);
        layer.alert('上传失败');
    });

    // 完成上传完了，成功或者失败，先删除进度条。
    uploader.on( 'uploadComplete', function( file ) {
        
    });

    // 监听文件上传事件
    $("#globalFilePicker").on("change", function (event) {
        console.log(event);
        var fileList = event.target.files; //获取文件对象 
        if (fileList && fileList.length > 0) {
            loadingIndex = layer.load(2);
            uploader.addFile(fileList);
        }
    });

    // 监听剪切板
    $(document).on("paste", function (e) {
        console.log(e);
        var clipboardData = e.clipboardData || e.originalEvent && e.originalEvent.clipboardData || {};
        // console.log(clipboardData);

        if (clipboardData.items) {
            arrForEach(clipboardData.items, function (item, index) {
                var value = item.value;
                // console.log(item, value);
                if (/image/i.test(item.type)) {
                    // 阻断编辑
                    var index = layer.load(1);
                    console.log(item);
                    var blob = item.getAsFile();
                    xnote.uploadBlob(blob, 'msg', function (respJson) {
                        console.log(respJson);
                        var link = "file://" + respJson.webpath;
                        var result = {link: link};
                        xnote.fire("file.upload", result);
                        layer.close(index);
                    });
                }
            })
        }
    });
});
</script>
